<?php

namespace app\admin\controller;
use app\admin\model\UserModel;
use app\admin\model\UserType;
use think\Db;
use think\Session;

class User extends Base
{


    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            if(isset($role)&&$role != ""){
                $map['ag.id'] = $role;
            }
            if(isset($key)&&$key!="")
            {
                $map['a.username|a.real_name'] = ['like',"%" . $key . "%"];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['a.last_login_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['a.last_login_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['a.last_login_time'] = ['between time',[$start,$end]];
            }
            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;
            $field=input('field');
            $order=input('order');
            if($field && $order){
                $od="a.".$field." ".$order;
            }else{
                $od="a.create_time desc";
            }
            $user = new UserModel();
            $count = $user->getUserCount($map);
            $lists = $user->getUsersByWhere($map,$od, $Nowpage, $limits);
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        $role = Db::name('auth_group')->field('id,title')->order('create_time desc')->select();
        $this->assign ('role',$role);
        return $this->fetch("user/index");
    }



    public function userAdd()
    {
        if(request()->isPost()){
            $param = input('post.');
            $user = new UserModel();
            $param['password'] = md5(md5($param['password']) . config('auth_key'));
            $base64url = $param['portrait'];
            $res = base64_img($base64url,true);
            if($res['code'] == 200){
                $param['portrait'] = $res['msg'];
            }elseif($res['code'] == 100){
                return json($res);
            }
            $param['type'] = 2;
            $flag = $user->insertUser($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
        $role = new UserType();
        $sheng = Db::name('area')->where('level',1)->select ();
        $exclude = Db::name('admin')->where('groupid',2)->column ('area');
        return $this->fetch('user/useradd',['role'=>$role->getRole(),'sheng'=>$sheng,'range'=>implode (',',$exclude)]);
    }


    public function userQuAdd(){
        if(request()->isPost()){
            $param = input('post.');
            $user = new UserModel();
            $param['password'] = md5(md5($param['password']) . config('auth_key'));
            $base64url = $param['portrait'];
            $res = base64_img($base64url,true);
            if($res['code'] == 200){
                $param['portrait'] = $res['msg'];
            }elseif($res['code'] == 100){
                return json($res);
            }
            $param['type'] = 3;
            $param['integral'] = $param['pool'];
            if($param['sign_start'] <= date("Y-m-d")){
                $param['sign'] = 1;
            }else{
                $param['sign'] = 2;
            }
            $flag = $user->insertUser($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
        $role = new UserType();
        $sheng = Db::name('area')->where('level',3)->select ();
        $exclude = Db::name('admin')->where('groupid',3)->column ('area');
        return $this->fetch('user/user_qu_add',['role'=>$role->getRole(),'sheng'=>$sheng,'range'=>implode (',',$exclude)]);
    }


    public function checkName(){
        extract(input());
        if(isset($id)&&$id!=""){
            $uid = $id;
        }else{
            $uid = '';
        }
        $user = new UserModel();
        $flag =  $user->checkName ($username,$uid);
        return json(['code' => $flag['code'], 'msg' => $flag['msg']]);
    }


    public function userEdit()
    {
        $user = new UserModel();
        if(request()->isPost()){
            $param = input('post.');
            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = md5(md5($param['password']) . config('auth_key'));
            }
            $base64url = $param['portrait'];
            $res = base64_img($base64url,true);
            $have = "";
            if($res['code'] == 200){
                $param['portrait'] = $res['msg'];
                if(session('uid')==$param['id']){
                    $have = "have";
                }
            }elseif($res['code'] == 100){
                return json($res);
            }
            if(isset($param['sign_start']) && $param['sign_start'] <= date("Y-m-d")){
                $param['sign'] = 1;
            }else{
                $param['sign'] = 2;
            }
            $flag = $user->editUser($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg'],'type'=>$have]);
        }
        $id = input('param.id');
        if($id != "1"){
            $role = new UserType();
            $this->assign([
                'user' => $user->getOneUser($id),
                'role' => $role->getRole()
            ]);
            //普通管理员编辑页面
            return $this->fetch("user/useredit");
        }else{
            $this->assign([
                'user' => $user->getOneUser($id)
            ]);
            //超级管理员编辑页面
            return $this->fetch("user/editadmin");
        }

    }


    public function adminEdit(){
        $user = new UserModel();
        $oldpassword = md5(md5(input('oldpassword')).config('auth_key'));
        if(input('type')=="checkPassword"){
            $flag =  $user->checkOldPassword ($oldpassword,session('uid'));
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }else{
            $param = input('post.');
            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = md5(md5($param['password']) . config('auth_key'));
            }
            $base64url = $param['portrait'];
            $res = base64_img($base64url,true);
            $have = "";
            if($res['code'] == 200){
                $param['portrait'] = $res['msg'];
                //判断编辑的是不是自己的头像
                if(session('uid')==$param['id']){
                    $have = "have";
                }
            }elseif($res['code'] == 100){
                return json($res);
            }
            $flag = $user->editUser($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg'],'type'=>$have]);
        }
    }


    public function UserDel()
    {
        $id = input('param.id');
        if(session('uid')==$id){
            return json(['code'=>100,'msg'=>'不能删除自己']);
        }else{
            $role = new UserModel();
            $flag = $role->delUser($id);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
    }


    public function user_state()
    {
        extract(input());
        $role = new UserModel();
        $flag = $role->userState($id,$num);
        return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
    }


    public function theme(){
        $type =  input('id');
        $param['theme'] = $type;
        $role = new UserModel();
        $flag = $role->changeTheme($param);
        return json(['code' => $flag['code'],'msg' => $flag['msg']]);
    }


    public function editPwd(){
        extract(input());
        $user = new UserModel();
        if(isset($type) && $type=='checkPassword'){
            $old_pwd = md5(md5($old_pwd).config('auth_key'));
            return json($user->checkOldPassword ($old_pwd,session('uid')));
        }else{
            $param['password'] = md5(md5($new_pwd).config('auth_key'));
            $flag = $user->editPassword($param);
            return json(['code'=>$flag['code'],'msg'=>$flag['msg']]);
        }
    }



    public function getArea(){
        extract (input());
        $pid = Db::name('area')->where('district_id',$qu)->value('pid');
        $shi = Db::name('area')->where('district_id',$pid)->field('district_id,district,pid')->find();
        $sheng = Db::name('area')->where('district_id',$shi['pid'])->field('district_id,district')->find();
        return json(['code'=>200,'sheng'=>$sheng,'shi'=>$shi]);
    }


    public function getMoney(){
        extract (input());
        $user = Db::name('u_user')->where('user_phone',$phone)->find();
        if(empty($user)){
            return json(['code'=>100,'msg'=>"提现账户不存在"]);
        }
        $admin = Db::name('admin')->where('id',session('uid'))->find();
        if($admin['balance'] <= 0){
            return json(['code'=>100,'msg'=>"余额不足"]);
        }
        if($money > $admin['balance']){
            return json(['code'=>100,'msg'=>"提现金额不可大于可提现余额"]);
        }
		if($user['user_level'] != 2){
            return json(['code'=>100,'msg'=>"不是城市合伙人"]);
        }
        Db::startTrans ();
        try{
            Db::name('u_user')->where('user_id',$user['user_id'])->setInc ('user_balance',$money);
            Db::name ('admin')->where('id',$admin['id'])->setDec ('balance',$money);
            Db::commit ();
            return json(['code'=>200,'msg'=>"提现成功"]);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['code'=>100,'msg'=>"提现失败"]);
        }
    }

    
    public function test(){
        return $this->fetch ('user/test');
    }
    /**
     * 倒计时编辑
     * @return mixed|\think\response\Json
     */
    public function updateDays(){
        $id = input('id');
        $param = [
            'admin_days'=>input('value'),
        ];
        $res = Db::name('admin')->where('id',$id)->update($param);
        if($res){
            return json(['code' => 200, 'msg' => '修改成功']);
        }else{
            return json(['code' => 100, 'msg' =>' 修改失败']);
        }
    }
}